package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.AddressDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Address;
import com.itheima.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service(interfaceClass = AddressService.class)
@Transactional
public class AddressServiceImpl implements AddressService {
    @Autowired
    private AddressDao addressDao;

    @Override
    public void add(Address address) {
        String address1 = address.getAddress();
        String jsonString = jsonString(address1);
        address.setAddress(jsonString);
        addressDao.add(address);
        //setOrderAndAddress(checkGroup.getId(),checkitemIds);
    }

    /*去除双引号方法*/
    private static String jsonString(String s) {
        return s.replaceAll("\"", "");
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        PageHelper.startPage(currentPage, pageSize);
        Page<Address> page = addressDao.findPage(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public Address findById(Integer id) {
        return addressDao.findById(id);
    }

    @Override
    public void update(Address address) {
        String address1 = address.getAddress();
        String jsonString = jsonString(address1);
        address.setAddress(jsonString);
        addressDao.update(address);
    }

    @Override
    public void delete(Integer id) {
        //判断此地址是否有套餐关联
        Integer count = addressDao.findOrderIdByAddressId(id);
        if (count>0) {
            throw new RuntimeException("当前项被"+count+"个套餐引用,不能删除");
        }
        addressDao.delete(id);
    }

    @Override
    public List<Address> findAddress() {
        return addressDao.findAddress();
    }

    @Override
    public List<Address> findByIds(Integer[] ids) {
        return addressDao.findByIds(ids);
    }

    @Override
    public List<Map<String, Object>> findCityCount() {
        return addressDao.findCityCount();
    }

    @Override
    public List<Address> findAddressAll() {
        return addressDao.findAddress();
    }
}
